package com.smmisia.article.asept;

import com.smmisia.article.aop.RequestLock;
import com.smmisia.common.Result.Result;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.types.Expiration;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;

/**
 * @description 缓存实现
 */
@Aspect
@Configuration
@Order(2)
public class RedisRequestLockAspect {

    // 注入StringRedisTemplate
    private final StringRedisTemplate stringRedisTemplate;

    @Autowired
    public RedisRequestLockAspect(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    // 定义切面，拦截所有带有RequestLock注解的方法
    @Around("execution(public * * (..)) && @annotation(com.smmisia.article.aop.RequestLock)")
    public Object interceptor(ProceedingJoinPoint joinPoint) {
        // 获取方法签名
        MethodSignature methodSignature = (MethodSignature)joinPoint.getSignature();
        // 获取方法
        Method method = methodSignature.getMethod();
        // 获取RequestLock注解
        RequestLock requestLock = method.getAnnotation(RequestLock.class);
        // 判断前缀是否为空
        if (StringUtils.isEmpty(requestLock.prefix())) {
            return Result.fail("重复提交前缀不能为空");
        }
        // 获取自定义key
        final String lockKey = RequestKeyGenerator.getLockKey(joinPoint);
        // 使用RedisCallback接口执行set命令，设置锁键；设置额外选项：过期时间和SET_IF_ABSENT选项
        final Boolean success = stringRedisTemplate.execute(
                (RedisCallback<Boolean>) connection -> connection.set(lockKey.getBytes(), new byte[0],
                        Expiration.from(requestLock.expire(), requestLock.timeUnit()),
                        RedisStringCommands.SetOption.SET_IF_ABSENT));
        // 判断是否设置成功
        if (!success) {
            return Result.fail("您的操作太快了,请稍后重试");
        }
        try {
            // 执行方法
            return joinPoint.proceed();
        } catch (Throwable throwable) {
            return Result.fail("系统异常");
        }
    }
}